<script setup>
import { ref } from 'vue'
import {
  ToggleHotSceneryService,
  ToggleHotHotelService,
  ToggleHotRestaurantService,
  deleteSceneryService,
  deleteHotelService,
  deleteRestaurantService,
  getSceneryDetailService,
  getHotelDetailService,
  getRestaurantDetailService
} from '@/apis/travel'

import { ToggleHotPostService, deletePostService } from '@/apis/post'
import {
  setUserMuteService,
  banUserAccountService,
  unbanUserAccountService
} from '@/apis/user'
import FormComponent from '@/components/FormComponent.vue'
import dayjs from 'dayjs'

// 控制抽屉弹出
const is_show = ref(false)

// 传递给表单组件的表单数据
const formData = ref(null)

// 获取表单组件实例
const formRef = ref(null)

// 设置禁言下拉框选项
const options = ref([
  {
    value: '1m',
    label: '1分钟'
  },
  {
    value: '3d',
    label: '3天'
  },
  {
    value: '7d',
    label: '7天'
  },
  {
    value: '30d',
    label: '30天'
  }
])

const props = defineProps({
  list: {
    type: Array,
    required: true
  },
  type_key: {
    type: String,
    default: ''
  },
  template_key: {
    type: String,
    required: true
  }
})

// 向父组件提交更新列表事件
const emit = defineEmits(['updateList'])

// 门景点、酒店、餐厅热门状态切换
const addHotFun = async (row) => {
  if (props.template_key === 'travel') {
    switch (props.type_key) {
      case '景点':
        await ToggleHotSceneryService(row.id)
        break
      case '酒店':
        await ToggleHotHotelService(row.id)
        break
      case '餐厅':
        await ToggleHotRestaurantService(row.id)
        break
    }
    ElMessage.success(`添加热门${props.type_key}成功`)
  } else if (props.template_key === 'post') {
    await ToggleHotPostService(row.id)
    ElMessage.success(`添加热门攻略成功`)
  }
  emit('updateList')
}

// 编辑数据
const editorData = async (row) => {
  showDrawer()

  // 获取表单数据
  switch (props.type_key) {
    case '景点':
      formData.value = await getSceneryDetailService(row.id)
      break
    case '酒店':
      formData.value = await getHotelDetailService(row.id)
      break
    case '餐厅':
      formData.value = await getRestaurantDetailService(row.id)
      break
  }
}

// 删除数据
const deleteData = async (row) => {
  await ElMessageBox.confirm('你确定要删除该条数据吗？', '温馨提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })

  if (props.template_key === 'travel') {
    switch (props.type_key) {
      case '景点':
        await deleteSceneryService(row.id)
        break
      case '酒店':
        await deleteHotelService(row.id)
        break
      case '餐厅':
        await deleteRestaurantService(row.id)
        break
    }
  } else if (props.template_key === 'post') {
    await deletePostService(row.id)
  }

  ElMessage.success('删除成功')
  emit('updateList')
}

// 点击切换取消热门状态
const onChangeStatus = async (row) => {
  if (row.is_hot) {
    await ElMessageBox.confirm('你确定要移除当前热门状态吗？', '温馨提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    })

    if (props.template_key === 'travel') {
      switch (props.type_key) {
        case '景点':
          await ToggleHotSceneryService(row.id)
          break
        case '酒店':
          await ToggleHotHotelService(row.id)
          break
        case '餐厅':
          await ToggleHotRestaurantService(row.id)
          break
      }
    } else if (props.template_key === 'post') {
      await ToggleHotPostService(row.id)
    }

    ElMessage.success('移除热门状态成功')
    emit('updateList')
  } else {
    return
  }
}

// 设置用户禁言时间
const onSelectionChange = async (row) => {
  await ElMessageBox.confirm('你确定要对该用户设置禁言吗？', '温馨提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
  await setUserMuteService({ id: row.user_id, mute_time: row.mute_duration })
  ElMessage.success('设置用户禁言成功')
  emit('updateList')
}

// 点击封禁/解封按钮设置用户账号封禁状态
const onClickBanButton = async (row) => {
  if (row.status === '正常' || row.status === '禁言') {
    await ElMessageBox.confirm('你确定要封禁该用户账号吗？', '温馨提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await banUserAccountService({ id: row.user_id })
    ElMessage.success('封禁用户账号成功')
    emit('updateList')
  } else {
    await ElMessageBox.confirm('你确定要解封该用户账号吗？', '温馨提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await unbanUserAccountService({ id: row.user_id })
    ElMessage.success('解封用户账号成功')
    emit('updateList')
  }
}

// 弹出抽屉组件
const showDrawer = () => {
  is_show.value = true
}

// 关闭抽屉组件
const onCloseDrawer = () => {
  is_show.value = false
  formRef.value.clearFormModel()
  emit('updateList')
}

// 向父组件暴露子组件的方法
defineExpose({
  showDrawer
})
</script>

<template>
  <template v-if="template_key === 'travel'">
    <div>
      <!-- 列表组件 -->
      <el-table
        :data="props.list"
        style="width: 100%"
        v-loading="isLoading"
        v-if="props.list?.length"
        :header-cell-style="{ 'text-align': 'center' }"
        :cell-style="{ 'text-align': 'center' }"
      >
        <el-table-column prop="date" type="index" label="序号" width="60" />
        <el-table-column :label="type_key + '名称'" width="150">
          <template #default="{ row }">
            <div class="ellipsis">
              {{ row.name }}
            </div>
          </template>
        </el-table-column>
        <el-table-column :label="type_key + '图片'">
          <template #default="{ row }">
            <el-image
              style="width: 120px; height: 85px"
              :src="row.image[0]"
              :preview-src-list="[...row.image]"
              preview-teleported
              fit="cover"
              lazy
            />
          </template>
        </el-table-column>
        <el-table-column prop="city" label="所在城市" />
        <el-table-column prop="rating" :label="type_key + '评分'" />
        <el-table-column
          prop="grade"
          v-if="type_key !== '餐厅'"
          :label="type_key + '等级'"
        />
        <el-table-column prop="type" :label="type_key + '类型'" />
        <el-table-column
          :label="
            type_key === '景点'
              ? '门票价格'
              : type_key === '酒店'
                ? '酒店价格'
                : '餐厅价格'
          "
        >
          <template #default="{ row }">
            {{ Math.floor(row.price) }}元
          </template>
        </el-table-column>
        <el-table-column label="热门状态">
          <template #default="{ row }">
            <el-tag
              :type="row.is_hot ? 'success' : 'info'"
              effect="dark"
              size="large"
              round
              @click="onChangeStatus(row)"
              >{{
                row.is_hot === 1 ? '热门' + type_key : '普通' + type_key
              }}</el-tag
            >
          </template>
        </el-table-column>

        <el-table-column label="操作" width="150">
          <template #default="{ row }">
            <el-button type="primary" circle @click="editorData(row)">
              <template #icon>
                <i-ep-Edit></i-ep-Edit>
              </template>
            </el-button>
            <el-button type="danger" circle @click="deleteData(row)">
              <template #icon>
                <i-ep-Delete></i-ep-Delete>
              </template>
            </el-button>
            <el-button
              v-if="row.is_hot === 0"
              type="success"
              circle
              @click="addHotFun(row)"
            >
              <template #icon>
                <i-ep-Plus></i-ep-Plus>
              </template>
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-empty v-else :image-size="400" />
    </div>
  </template>

  <template v-else-if="template_key === 'post'">
    <div>
      <!-- 列表组件 -->
      <el-table
        :data="props.list"
        style="width: 100%"
        v-loading="isLoading"
        v-if="props.list?.length"
        :header-cell-style="{ 'text-align': 'center' }"
        :cell-style="{ 'text-align': 'center' }"
      >
        <el-table-column prop="date" type="index" label="序号" width="60" />
        <el-table-column label="攻略标题" width="300">
          <template #default="{ row }">
            <div class="ellipsis">
              {{ row.title }}
            </div>
          </template>
        </el-table-column>
        <el-table-column :label="type_key + '图片'">
          <template #default="{ row }">
            <el-image
              style="width: 120px; height: 85px"
              :src="row.image[0]"
              :preview-src-list="[...row.image]"
              preview-teleported
              fit="cover"
              lazy
            />
          </template>
        </el-table-column>
        <el-table-column label="用户名">
          <template #default="{ row }">
            {{
              row.username === '' || row.username === null
                ? '乐游汇用户'
                : row.username
            }}
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="用户手机号" />
        <el-table-column prop="createdAt" label="发布时间">
          <template #default="{ row }">
            {{ dayjs(row.createdAt).format('YYYY-MM-DD hh:mm:ss') }}
          </template>
        </el-table-column>
        <el-table-column label="热门状态">
          <template #default="{ row }">
            <el-tag
              :type="row.is_hot ? 'success' : 'info'"
              effect="dark"
              size="large"
              round
              :checked="row.is_hot"
              @click="onChangeStatus(row)"
              >{{ row.is_hot === 1 ? '热门攻略' : '普通攻略' }}</el-tag
            >
          </template>
        </el-table-column>

        <el-table-column label="操作" width="150">
          <template #default="{ row }">
            <el-button type="danger" circle @click="deleteData(row)">
              <template #icon>
                <i-ep-Delete></i-ep-Delete>
              </template>
            </el-button>
            <el-button
              v-if="row.is_hot === 0"
              type="success"
              circle
              @click="addHotFun(row)"
            >
              <template #icon>
                <i-ep-Plus></i-ep-Plus>
              </template>
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-empty v-else :image-size="400" />
    </div>
  </template>

  <template v-else-if="template_key === 'user'">
    <div>
      <!-- 列表组件 -->
      <el-table
        :data="props.list"
        style="width: 100%"
        v-loading="isLoading"
        v-if="props.list?.length"
        :header-cell-style="{ 'text-align': 'center' }"
        :cell-style="{ 'text-align': 'center' }"
      >
        <el-table-column prop="date" type="index" label="序号" width="60" />
        <el-table-column label="用户名">
          <template #default="{ row }">
            {{
              row.username === '' || row.username === null
                ? '乐游汇用户'
                : row.username
            }}
          </template>
        </el-table-column>
        <el-table-column label="用户头像">
          <template #default="{ row }">
            <el-image
              style="width: 120px; height: 85px"
              :src="row.avatar"
              :preview-src-list="[row.avatar]"
              preview-teleported
              fit="cover"
              lazy
            />
          </template>
        </el-table-column>
        <el-table-column prop="name" label="用户姓名">
          <template #default="{ row }">
            <div v-if="row.name">{{ row.name }}</div>
            <div v-else>暂无</div>
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="用户手机号" />
        <el-table-column prop="email" label="用户邮箱">
          <template #default="{ row }">
            <div v-if="row.email">{{ row.email }}</div>
            <div v-else>暂无</div>
          </template>
        </el-table-column>
        <el-table-column label="账号状态">
          <template #default="{ row }">
            <el-tag
              :type="
                row.status === '正常'
                  ? 'success'
                  : row.status === '禁言'
                    ? 'warning'
                    : 'danger'
              "
              effect="dark"
              size="large"
              round
              >{{ row.status }}</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column label="操作" width="230">
          <template #default="{ row }">
            <div class="operate">
              <el-select
                v-model="row.mute_duration"
                placeholder="设置禁言"
                style="width: 100px"
                @change="onSelectionChange(row)"
              >
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
              <el-button
                @click="onClickBanButton(row)"
                :type="row.status === '封禁' ? 'success' : 'danger'"
                >{{
                  row.status === '封禁' ? '解除封禁' : '封禁账号'
                }}</el-button
              >
            </div>
          </template>
        </el-table-column>
      </el-table>

      <el-empty v-else :image-size="400" />
    </div>
  </template>

  <el-drawer
    v-model="is_show"
    :title="'编辑' + type_key"
    @open="showDrawer"
    @close="onCloseDrawer"
  >
    <FormComponent
      ref="formRef"
      :type="type_key"
      :formData="formData?.data"
      @closeDrawer="onCloseDrawer"
    ></FormComponent>
  </el-drawer>
</template>

<style lang="scss" scoped>
.operate {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
